package com.maybach.workflow.core.processor.impl;


import com.maybach.workflow.common.api.FlowHandlerFactory;
import com.maybach.workflow.common.api.IInterceptor;
import com.maybach.workflow.common.api.WorkFlowContext;
import com.maybach.workflow.common.api.enums.FlowStateEnum;
import com.maybach.workflow.common.api.node.BaseNode;
import com.maybach.workflow.common.api.node.EndNode;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by houenxun on 15/8/13.
 */
public class EndProcessor extends AbstractProcessor {


    private List<IInterceptor> runOutInInterceptor;

    @Override
    public boolean runIn(WorkFlowContext workFlowContext) {
        this.runOut(workFlowContext);
        return true;
    }

    @Override
    public List<BaseNode> getNextNodes(WorkFlowContext workFlowContext) {
        List<BaseNode> list = new ArrayList<BaseNode>();
        list.add(workFlowContext.getThisNode());
        return list;
    }

    @Override
    public void runOut(WorkFlowContext workFlowContext) {
        BaseNode thisNode = workFlowContext.getThisNode();
        // 处理流程中定义的handler
        FlowHandlerFactory.handle(((EndNode) thisNode).getHandlers(), workFlowContext);
        flowRepository.updateFlowStatus(workFlowContext.getThisFlow().getId(), FlowStateEnum.end.getStatus());
        logFlow(thisNode, "流程完成", super.getThisTaskId(workFlowContext));
        /**
         * 执行创建任务后的额外逻辑 可插拔
         */
        if (CollectionUtils.isNotEmpty(runOutInInterceptor)) {
            for (IInterceptor interceptor : runOutInInterceptor) {
                interceptor.execute(workFlowContext);
            }
        }
    }

    public void setRunOutInInterceptor(List<IInterceptor> runOutInInterceptor) {
        this.runOutInInterceptor = runOutInInterceptor;
    }

    public List<IInterceptor> getRunOutInInterceptor() {
        return runOutInInterceptor;
    }
}
